// pages/fx/fx.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageRoot: app.globalData.imageRoot,
    painting: {},
    status: null,
    avatar: '', //头像
    wxqrcode: '', //二维码图片
    bannerImg: '', //大图
    title: '', //标题
    price: '', //总价
    area: '', //面积
    discount: '', //折扣
    inviNum: '', //邀请人数
    name: '', //姓名
    telphone: '', //联系方式
    shareImage: '',
    userId: '',
    canvas: '',
    backgroundImage: '',  //背景图片
  },
  navBack: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  getModelConfig(){
    let that = this;
    getApp().ports.modelConfig({data:{modelPosition: 7}}).then((res) => {
      that.setData({
        backgroundImage: app.globalData.imageRoot + res.data.imageUrl
      })
    })
  },
  //点击保存图片
  getInfo() { //拉取自身信息
    wx.showLoading({
      title: '正在生成海报',
    })
    var that = this;
    getApp().ports.userIdentity({}).then((res) => {
      var res = res.data;
      let inviId = that.data.id //自身id
      wx.downloadFile({ //头像处理
        url: res.avatarUrl,
        success: function (res) {
          Object.assign(that.data,{
            avatar: res.tempFilePath
          })
        }
      })
      that.setData({
        userId: that.data.id,
        name: res.nickname,
        // name:'快啦就打架啊来得及爱丽丝开机的埃里克时代静安寺垃圾的',
        telphone: res.phone
      }) //按钮分享用
      let appid = app.globalData.appid;
      let json = {
        category: 'getwxacodeunlimit'
      } //有个数限制
      let data = {
        appid: appid, //小程序id
        path: "pages/details/details", //扫码进入那个页面
        params: JSON.stringify({
          userId: res.id,
          id: inviId,
          status: that.data.status
        }) //可以传输多个值
      }
      app.ports.apiqrcode({
        data,
        json
      }).then((res) => {
        // let base64 = wx.arrayBufferToBase64(res.data)
        let fsm = wx.getFileSystemManager();
        // let showImgData = base64

        // that.setData({ imgurl : 'data:image/png;base64,'+res11.data})
        let showImgData = res.data;
        showImgData = showImgData.replace(/\ +/g, ""); //去掉空格方法
        showImgData = showImgData.replace(/[\r\n]/g, "");
        let buffer = wx.base64ToArrayBuffer(showImgData);
        let fileName = wx.env.USER_DATA_PATH + '/share_img.png'
        fsm.writeFileSync(fileName, buffer,'binary');
        that.setData({
          wxqrcode: fileName
        })
        // that.eventDraw()
        that.canvas()
      }).catch(() => {
        console.error('生成二维码错误！')
      })
      that.setData({
        userId: res.id,
        user: res
      })
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  async api(data) {
    var that = this;
    var admin = that.data.admin
    var status = that.data.status;
    var arr = [0,2,3]
    if (status == 0) {
      if (arr.includes(admin)) {
      await  getApp().ports.fpxqAdmin({
          data: data
        }).then(async (res) => {
          var res = res.data;
          res.priceYuan = Math.floor((res.priceYuan / 10000));
          res.marketPriceYuan = Math.floor((res.marketPriceYuan / 10000));
          res.estimatePriceYuan = Math.floor((res.estimatePriceYuan / 10000));
          that.setData({
            list: res,     
          })
          if (res.banner) {
            wx.getImageInfo({ //主图处理
              src: res.banner,
              success: function (data) {
                Object.assign(that.data,{
                  bannerImg: data.path
                })
              }
            })
          }
        }).catch(() => {
          console.error('出啥错了？');
        });
      } else {
        await getApp().ports.fpxq({
          data: data
        }).then(async (res) => {
          var res = res.data;
          res.priceYuan = Math.floor((res.priceYuan / 10000));
          res.marketPriceYuan = Math.floor((res.marketPriceYuan / 10000));
          res.estimatePriceYuan = Math.floor((res.estimatePriceYuan / 10000));
          res.title = '['+res.residentialQuarterName +']' + res.title;
          that.setData({
            list: res
          })
          if (res.banner) {
            wx.getImageInfo({ //主图处理
              src: res.banner,
              success: function (data) {
                that.setData({
                  bannerImg: data.path
                })
                console.log(that.data.bannerImg, '====')
              }
            })
          }
        }).catch(() => {
          console.error('出啥错了？');
        });
      }
    } else {
      // var statuss = ['', '出售中', '已出售'];
      if (arr.includes(admin)) {
       await getApp().ports.zkxqAdmin({
          data: data
        }).then(async (res) => {
          var res = res.data;
          // res.priceYuan = Math.floor((res.priceYuan / 10000));
          // res.marketPriceYuan = Math.floor((res.marketPriceYuan / 10000));
          // res.estimatePriceYuan = Math.floor((res.estimatePriceYuan / 10000));
          res.title = '['+res.residentialQuarterName +']' + res.title;
          that.setData({
            price: res.priceYuan,
            list: res,
            title: res.title,
            inviNum: res.browseCount,
            discount: res.discountRate,
            area: res.builtUpAreaSquareCentimeter,
          })
          if (res.banner) {
            wx.getImageInfo({ //主图处理
              src: that.data.imageRoot + res.banner,
              success: function (data) {
                that.setData({
                  bannerImg: data.path
                })
                console.log(that.data.bannerImg, '====')
              }
            })
          }
        }).catch(() => {
          console.error('出啥错了？');
        });
      } else if (admin == 1) {
       await getApp().ports.zkxq({
          data: data
        }).then(async (res) => {
          var res = res.data;
          that.setData({
            price: res.priceYuan,
            list: res,
            title: res.title,
            inviNum: res.browseCount,
            discount: res.discountRate,
            area: res.builtUpAreaSquareCentimeter,
          })
          if (res.banner) {
            wx.getImageInfo({ //主图处理
              src: that.data.imageRoot + res.banner,
              success: function (data) {
                that.setData({
                  bannerImg: data.path
                })
                console.log(that.data.bannerImg, '====')
              }
            })
          }
        }).catch(() => {
          console.error('出啥错了？');
        });
      } else {
        wx.showToast({
          title: `不明类型 status=${status}`,
          icon: 'none'
        })
      }
    }
  },
  canvas() {
    var that = this;
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        that.data.canvas = canvas
        const ctx = canvas.getContext('2d')
        console.log(ctx)
        const dpr = wx.getSystemInfoSync().pixelRatio
        that.data.canvasWidth = res[0].width * dpr;
        that.data.canvasHeight = res[0].height * dpr
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.fillStyle = "#fff"
        ctx.scale(dpr, dpr)
        ctx.fillRect(0, 0, app.globalData.system.windowWidth - (app.globalData.system.windowWidth / 5.5), app.globalData.system.windowHeight)

        that.drawBg(canvas, ctx); // 绘制图片

        that.houseTitle(canvas, ctx);
        that.house(canvas, ctx) // 绘制房源信息
        that.follow(canvas, ctx)
        that.canvasName(canvas,ctx)
        that.info(canvas, ctx)
        that.qrCode(canvas, ctx)
        wx.hideLoading({
          success: (res) => {},
        })
      })
  },
  houseTitle(canvas, ctx) {
    var that = this;
    var text = that.data.list.title; //这是要绘制的文本
    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif";
    ctx.fillStyle = "#000"
    for (var a = 0; a < chr.length; a++) {
      if (ctx.measureText(temp).width < 280) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (ctx.measureText(test).width < app.globalData.system.windowWidth - (app.globalData.system.windowWidth / 3)) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      ctx.fillText(row[b], app.globalData.system.windowWidth / 20, app.globalData.system.windowHeight/2.6 + b * 30, app.globalData.system.windowWidth - (app.globalData.system.windowWidth / 3));
    }
    // ctx.draw()
  },
  drawBg(canvas, ctx) {
    var that = this;
    console.log(that.data.bannerImg)
    console.log('调用成功')
    const img = canvas.createImage()
    img.src = that.data.bannerImg
    console.log(img)
    img.onload = () => {
      ctx.drawImage(img, 0, 0, app.globalData.system.windowWidth - (app.globalData.system.windowWidth / 5.5),app.globalData.system.windowHeight/2.94);
      console.log('成功')
    }
    // ctx.restore()
  },
  house(canvas, ctx) {
    var that = this;

    ctx.textAlign = 'center'
    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif"
    ctx.fillStyle = "red"
    ctx.fillText('总价', app.globalData.system.windowWidth / 10, app.globalData.system.windowHeight/2.1); //总价

    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif"
    ctx.fillStyle = "black"
   
    ctx.fillText('面积', app.globalData.system.windowWidth / 3.2, app.globalData.system.windowHeight/2.1); //面积

    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif"
    ctx.fillStyle = "#FFC728"
    ctx.fillText('折扣', app.globalData.system.windowWidth / 1.8, app.globalData.system.windowHeight/2.1); //折扣

    ctx.moveTo(app.globalData.system.windowWidth / 5.5, app.globalData.system.windowHeight/2.2)
    ctx.lineTo(app.globalData.system.windowWidth / 5.5,app.globalData.system.windowHeight/1.95)

    ctx.moveTo(app.globalData.system.windowWidth /2.2,app.globalData.system.windowHeight/2.2)
    ctx.lineTo(app.globalData.system.windowWidth / 2.2, app.globalData.system.windowHeight/1.95)
    ctx.stroke()

    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif"
    ctx.fillStyle = "red"
    ctx.fillText(that.data.list.priceYuan + '万', app.globalData.system.windowWidth / 10, app.globalData.system.windowHeight/1.96); //总价

    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif"
    ctx.fillStyle = "black"
    ctx.fillText(that.data.list.builtUpAreaSquareCentimeter + '㎡', app.globalData.system.windowWidth / 3.2, app.globalData.system.windowHeight/1.96); //面积

    ctx.font = app.globalData.system.windowHeight/49+"px sans-serif"
    ctx.fillStyle = "#FFC728"
    ctx.fillText(that.data.list.discountRate + '折', app.globalData.system.windowWidth / 1.8, app.globalData.system.windowHeight/1.96); //折扣

  },
  follow(canvas, ctx) {
    console.log('调用成功')
    // ctx.save()
    // const img = canvas.createImage()
    // img.src = 'https://test.imgs.vajump.com/images/canvas_03.png'
    // img.onload = () => {
    //   ctx.drawImage(img, 50, 390, 150, 40);
    //   ctx.save()
    // }
    ctx.strokeStyle = '#FEE4BB'
    ctx.beginPath()
    ctx.lineCap = 'round'
    ctx.lineWidth = '30'
    ctx.moveTo(app.globalData.system.windowWidth / 12, app.globalData.system.windowHeight/1.8)
    ctx.lineTo(app.globalData.system.windowWidth / 3.3, app.globalData.system.windowHeight/1.8)
    ctx.stroke()
    ctx.textAlign = 'left'
    ctx.font = app.globalData.system.windowHeight/56+"px sans-serif"
    ctx.fillStyle = "#F2BD7B"
    ctx.fillText(this.data.list.browseCount + '人已关注', app.globalData.system.windowWidth / 13,app.globalData.system.windowHeight/1.78, app.globalData.system.windowHeight/1.8); //关注人数

    ctx.font = "12px sans-serif"
    ctx.fillStyle = "#ccc"
    ctx.fillText('邀请好友提前看房', app.globalData.system.windowWidth / 2.5, app.globalData.system.windowHeight/1.78); //关注副标题
    ctx.restore();
  },
  info(canvas, ctx) {
    var that = this;
    const img = canvas.createImage()
    img.src = that.data.user.avatarUrl
    ctx.save();
    img.onload = () => {
      ctx.beginPath()
      // ctx.arc(50, 50, 470, 0, 2*Math.PI)
      ctx.arc(40 / 2 + app.globalData.system.windowWidth / 20, 40 / 2 + app.globalData.system.windowHeight/1.65, 40 / 2, 0, Math.PI * 2)
      ctx.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
      // ctx.drawImage(img, 60, 470, 40, 40);
      ctx.drawImage(img, app.globalData.system.windowWidth / 20, app.globalData.system.windowHeight/1.65, 40, 40);
      ctx.restore(); //可将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
    }
    ctx.font = app.globalData.system.windowHeight/56+"px sans-serif"
    ctx.fillStyle = "#000"
    // ctx.fillText(that.data.user.nickname, app.globalData.system.windowWidth / 4.5, app.globalData.system.windowHeight/1.6); //微信昵称
    ctx.font = app.globalData.system.windowHeight/56+"px sans-serif"
    ctx.fillStyle = "#000"
    ctx.fillText(that.data.user.phone, app.globalData.system.windowWidth /  5.5, app.globalData.system.windowHeight/1.53); //手机号
  },
  canvasName(canvas, ctx){
    var that = this;
    var text = that.data.name; //这是要绘制的文本
    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    ctx.font = "14px Arial"; // 设置字体大小
    ctx.fillStyle = "#333333"; // 设置文字颜色
    for (var a = 0; a < chr.length; a++) {
      if (ctx.measureText(temp).width < app.globalData.system.windowWidth - (app.globalData.system.windowWidth / 1.3)) {
        temp += chr[a];
      } else {
        temp+='...'
        break;
      }
    }
    console.log(temp)
   ctx.fillText(temp, app.globalData.system.windowWidth / 5.5, app.globalData.system.windowHeight/1.6); //微信昵称
  },
  onClose() {
    console.log('隐藏')
    this.data.ctx.clearRect(0,0, 1000,1000)
    this.setData({
      cardShow: false,
    })
  },
  qrCode(canvas, ctx) {
    var that = this;
    const img = canvas.createImage()
    console.log(that.data.wxqrcode, 'qrcode')
    img.src = that.data.wxqrcode
    img.onload = () => {
      ctx.drawImage(img, app.globalData.system.windowWidth / 1.8, app.globalData.system.windowHeight/1.7, app.globalData.system.windowHeight/9.2, app.globalData.system.windowHeight/9.2);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options)
    // that.data.bannerImg = options.imgurl
    that.setData({
      id: options.id,
      status: Number(options.status),
      admin:Number(options.admin),
      boxHeight:app.globalData.system.windowHeight*0.7
    })
    var data = {
      id: options.id
    }
    that.getModelConfig();
    
    that.api(data);
    that.getInfo();
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    var shareId = that.data.userId;
    console.log(shareId, that.data.status, that.data.id, '====================')
    //     if (res.from === 'button') {}
    return {
      title: that.data.list.title,
      path: 'pages/details/details?share=' + shareId + '&status=' + that.data.status + '&id=' + that.data.id,
      success: function (res) {
        console.log(res)
      }
    }
  },
  save() {
    console.log('保存图片')
    wx.canvasToTempFilePath({
      canvas: this.data.canvas, // 使用2D 需要传递的参数
      success(res) {
        console.log(res.tempFilePath)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功，请在相册中查看',
            })
          }
        })
      }
    })
  },
  eventSave() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImage,
      success(res) {
        wx.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
  eventGetImage(event) {
    //console.log(event)
    wx.hideLoading()
    const {
      tempFilePath,
      errMsg
    } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
  }
})